<template>
  <div class="bg-weather-secondary px-12 pt-10 mt-2 rounded">
    <div class="flex gap-6">
      <div
        class="flex flex-col flex-1 text-center gap-4"
        v-for="(item, index) in forecasthWeatherData"
        :key="index"
      >
        <span>{{ showDate(item.week) }}</span>
        <span>{{ item.date.slice(5, 10) }}</span>
        <span>{{ item.dayweather }}</span>
        <span>风力:{{ item.nightpower }}级</span>
      </div>
    </div>
    <div class="chartcanvas h-40 mt-10">
      <v-chart :option="searchoption"></v-chart>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
const props = defineProps({
  forecasthWeatherData: {
    type: Object,
    default: () => {}
  }
})
const searchoption = ref({})
// 定义星期数组
const weekArr = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
// 确定工作日
const showDate = (index) => {
  index = +index
  let today = new Date().getDay()
  if (index === today) {
    return '今天'
  } else if ((index - 1) % 7 === today) {
    return '明天'
  }
  // 否则返回对应的星期几名称
  else {
    return weekArr[index - 1]
  }
}
// 定义chartOption
const renderChart = (value) => {
  // 处理数据
  console.log('card数据', value)
  const data1 = value.map((item) => {
    return {
      name: '白',
      value: +item.daytemp
    }
  })
  const data2 = value.map((item) => {
    return {
      name: '晚',
      value: +item.nighttemp
    }
  })
  searchoption.value = {
    xAxis: {
      type: 'category',
      show: false
    },
    yAxis: {
      type: 'value',
      show: false
    },
    grid: {
      top: 20,
      left: 0,
      right: 0,
      bottom: 0
    },
    series: [
      // 白天气候
      {
        type: 'line',
        data: data1,
        label: {
          show: true,
          formatter: (params) => {
            return params.name + params.value + '°C'
          },
          color: '#fff'
        }
      },
      // 晚气候
      {
        type: 'line',
        data: data2,
        label: {
          show: true,
          formatter: (params) => {
            return params.name + params.value + '°C'
          },
          distance: -30,
          color: '#fff'
        }
      }
    ]
  }
}
onMounted(() => {
  if (props.forecasthWeatherData && Object.keys(props.forecasthWeatherData).length > 0) {
    renderChart(props.forecasthWeatherData)
  }
})
// 监听props变化
watch(props.forecasthWeatherData, (newData) => {
  if (newData && Object.keys(newData).length > 0) {
    renderChart(newData.value)
    console.log('card数据变化', data)
  }
},
{deep: true}
)
</script>

<style scoped>
.chartcanvas {
  user-select: none;
}
</style>
